{% extends "base.html" %}
{% load static %}

{% block title %}MQTT订阅列表{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>MQTT订阅列表</h2>
        <a href="{% url 'mqtt_subscription_add' %}" class="btn btn-primary">
            <i class="bi bi-plus-lg"></i> 添加订阅
        </a>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>数据源</th>
                            <th>主题</th>
                            <th>监控项</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for subscription in subscriptions %}
                        <tr>
                            <td>{{ subscription.data_source.name }}</td>
                            <td>{{ subscription.topic }}</td>
                            <td>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>名称</th>
                                                <th>数据键名</th>
                                                <th>报警条件</th>
                                                <th>阈值</th>
                                                <th>状态</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {% for item in subscription.mqttsubscriptionitem_set.all %}
                                            <tr>
                                                <td>{{ item.name }}</td>
                                                <td>{{ item.values_id }}</td>
                                                <td>{{ item.get_condition_display }}</td>
                                                <td>
                                                    {% if item.condition == 'range' %}
                                                        {{ item.threshold_value }} - {{ item.threshold_max }}
                                                    {% else %}
                                                        {{ item.threshold_value }}
                                                    {% endif %}
                                                </td>
                                                <td>
                                                    <span class="badge {% if item.is_active %}bg-success{% else %}bg-secondary{% endif %}">
                                                        {{ item.is_active|yesno:"启用,禁用" }}
                                                    </span>
                                                </td>
                                                <td>
                                                    <button type="button" 
                                                            class="btn btn-sm {% if item.is_active %}btn-outline-warning{% else %}btn-outline-success{% endif %} toggle-mqtt-item"
                                                            data-item-id="{{ item.id }}"
                                                            title="{% if item.is_active %}禁用{% else %}启用{% endif %}">
                                                        <i class="bi {% if item.is_active %}bi-pause-fill{% else %}bi-play-fill{% endif %}"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                            {% endfor %}
                                        </tbody>
                                    </table>
                                </div>
                            </td>
                            <td>
                                <span class="badge {% if subscription.is_active %}bg-success{% else %}bg-secondary{% endif %}">
                                    {{ subscription.is_active|yesno:"启用,禁用" }}
                                </span>
                            </td>
                            <td>
                                <div class="btn-group" role="group">
                                    <a href="{% url 'mqtt_subscription_edit' subscription.id %}" 
                                       class="btn btn-sm btn-outline-primary"
                                       title="编辑">
                                        <i class="bi bi-pencil"></i>
                                    </a>
                                    <a href="{% url 'mqtt_subscription_delete' subscription.id %}" 
                                       class="btn btn-sm btn-outline-danger"
                                       title="删除">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                    <button type="button" 
                                            class="btn btn-sm {% if subscription.is_active %}btn-outline-warning{% else %}btn-outline-success{% endif %} toggle-mqtt-subscription"
                                            data-subscription-id="{{ subscription.id }}"
                                            title="{% if subscription.is_active %}禁用{% else %}启用{% endif %}">
                                        <i class="bi {% if subscription.is_active %}bi-pause-fill{% else %}bi-play-fill{% endif %}"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="5" class="text-center text-muted">暂无订阅</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 处理MQTT订阅启用/禁用
        document.querySelectorAll('.toggle-mqtt-subscription').forEach(button => {
            button.addEventListener('click', function() {
                const subscriptionId = this.dataset.subscriptionId;
                const currentStatus = this.querySelector('i').classList.contains('bi-pause-fill');
                
                // 禁用按钮，防止重复点击
                this.disabled = true;
                
                // 发送请求到后端
                fetch(`/subscriptions/mqtt/${subscriptionId}/toggle/`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': '{{ csrf_token }}'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 更新按钮状态
                        this.title = currentStatus ? '启用' : '禁用';
                        this.classList.toggle('btn-outline-warning');
                        this.classList.toggle('btn-outline-success');
                        const icon = this.querySelector('i');
                        icon.classList.toggle('bi-pause-fill');
                        icon.classList.toggle('bi-play-fill');
                        
                        // 更新状态标签
                        const mainRow = this.closest('tr');
                        const statusBadge = mainRow.querySelector('td:nth-child(4) .badge');
                        if (statusBadge) {
                            statusBadge.className = `badge ${currentStatus ? 'bg-secondary' : 'bg-success'}`;
                            statusBadge.textContent = currentStatus ? '禁用' : '启用';
                        }
                        
                        // 显示成功消息
                        const message = `订阅已${data.status}`;
                        showAlert(message, 'success');
                    } else {
                        showAlert('操作失败：' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('操作失败，请重试', 'danger');
                })
                .finally(() => {
                    // 重新启用按钮
                    this.disabled = false;
                });
            });
        });

        // 处理MQTT监控项启用/禁用
        document.querySelectorAll('.toggle-mqtt-item').forEach(button => {
            button.addEventListener('click', function() {
                const itemId = this.dataset.itemId;
                const currentStatus = this.querySelector('i').classList.contains('bi-pause-fill');
                
                // 禁用按钮，防止重复点击
                this.disabled = true;
                
                // 发送请求到后端
                fetch(`/subscriptions/mqtt-item/${itemId}/toggle/`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': '{{ csrf_token }}'
                    },
                    body: JSON.stringify({
                        is_active: !currentStatus
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 更新按钮状态
                        this.title = currentStatus ? '启用' : '禁用';
                        this.classList.toggle('btn-outline-warning');
                        this.classList.toggle('btn-outline-success');
                        const icon = this.querySelector('i');
                        icon.classList.toggle('bi-pause-fill');
                        icon.classList.toggle('bi-play-fill');
                        
                        // 更新状态标签
                        const row = this.closest('tr');
                        const statusBadge = row.querySelector('.badge');
                        if (statusBadge) {
                            statusBadge.className = `badge ${currentStatus ? 'bg-secondary' : 'bg-success'}`;
                            statusBadge.textContent = currentStatus ? '禁用' : '启用';
                        }
                        
                        // 显示成功消息
                        const message = `监控项已${data.status}`;
                        showAlert(message, 'success');
                    } else {
                        showAlert('操作失败：' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('操作失败，请重试', 'danger');
                })
                .finally(() => {
                    // 重新启用按钮
                    this.disabled = false;
                });
            });
        });

        // 显示提示消息
        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;
            document.querySelector('.container').insertBefore(alertDiv, document.querySelector('.card'));
            
            // 3秒后自动关闭提示
            setTimeout(() => {
                alertDiv.remove();
            }, 3000);
        }
    });
</script>
{% endblock %}
 